<?php

namespace App\Jobs;

use App\Http\Controllers\Api\StarController;
use App\Models\Article;
use App\Models\Star;
use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Http\Request;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class RandStarJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    private $article_id;

    private $user_id;

    /**
     * RandStarJob constructor.
     * @param $article_id
     * @param $user_id
     */
    public function __construct($article_id, $user_id = 0)
    {
        $this->article_id = $article_id;
        $this->user_id = $user_id;
    }

    /**
     * @throws \App\Exceptions\BlackException
     * @throws \Illuminate\Validation\ValidationException
     * @throws \Throwable
     */
    public function handle()
    {
        \Log::info('start-rand-star');
        $article = Article::find($this->article_id);
        if (!$article || $article->status != Article::STATUS_NORMAL) {
            \Log::error('article_id not valid ' . $this->article_id);
            return;
        }

        if (!$this->user_id) {
            $user = User::where('is_virtual', 1)->inRandomOrder()->take(1)->first();
        } else {
            $user = User::find($this->user_id);
        }
        if (!$user) {
            \Log::error('user is_virtual not exists');
            return ;
        }

        $request = app(Request::class);
        $exists = Star::where('user_id', $user->id)->where('type', Star::TYPE_ARTICLE)->where('entity_id', $this->article_id)->exists();
        if (!$exists) {
            $request->merge(['entity_id' => $this->article_id, 'type' => Star::TYPE_ARTICLE]);
            $star = new StarController();
            $star->store($request, $user);
        }
        \Log::info('start-end-star');
    }
}
